package org.club.common.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.context.annotation.Bean;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import javax.annotation.PreDestroy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketConfig.class);
    private ThreadPoolTaskScheduler taskScheduler;

    @Bean
    public TaskScheduler stompTaskScheduler() {
        taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(1);
        taskScheduler.setThreadNamePrefix("MessageBroker-");
        taskScheduler.setRemoveOnCancelPolicy(true);
        taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
        taskScheduler.setAwaitTerminationSeconds(10);
        taskScheduler.initialize();
        return taskScheduler;
    }

    @PreDestroy
    public void destroy() {
        if (taskScheduler != null) {
            logger.info("正在关闭WebSocket任务调度器...");
            try {
                // 先关闭
                taskScheduler.shutdown();
                
                // 确保调度器的ExecutorService完全关闭
                if (!taskScheduler.getScheduledExecutor().isTerminated()) {
                    logger.info("等待WebSocket任务完成...");
                    if (!taskScheduler.getScheduledExecutor().awaitTermination(10, TimeUnit.SECONDS)) {
                        logger.warn("WebSocket任务未在指定时间内完成，强制关闭");
                        taskScheduler.getScheduledExecutor().shutdownNow();
                    }
                }
            } catch (InterruptedException e) {
                logger.error("关闭WebSocket任务调度器时被中断", e);
                taskScheduler.getScheduledExecutor().shutdownNow();
                Thread.currentThread().interrupt();
            } catch (Exception e) {
                logger.error("关闭WebSocket任务调度器时发生异常", e);
                taskScheduler.getScheduledExecutor().shutdownNow();
            }
            logger.info("WebSocket任务调度器已关闭");
        }
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 注册STOMP端点
        registry.addEndpoint("/ws")
                .setAllowedOrigins("http://localhost:5173") // 允许的前端域名
                .withSockJS(); // 启用SockJS支持
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        // 配置消息代理
        // 客户端订阅前缀
        registry.enableSimpleBroker("/topic", "/queue")
                .setTaskScheduler(stompTaskScheduler())
                .setHeartbeatValue(new long[] {10000, 10000});
        // 客户端发送消息前缀
        registry.setApplicationDestinationPrefixes("/app");
        // 点对点消息前缀
        registry.setUserDestinationPrefix("/user");
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new ChannelInterceptor() {
            @Override
            public Message<?> preSend(Message<?> message, MessageChannel channel) {
                StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
                
                if (StompCommand.CONNECT.equals(accessor.getCommand())) {
                    String user = accessor.getFirstNativeHeader("user");
                    if (user != null) {
                        UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
                            user, null, Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
                        );
                        accessor.setUser(auth);
                    }
                }
                return message;
            }
        });
    }
} 